package com.luoye.lj.util.converter;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;

/**
 * Created with IntelliJ IDEA.
 * User: Dave Liu
 * Date: 2015/12/21
 * Time: 20:28
 * Bean转换器，主要用于Pb对象转实体对象
 */
public class BeanConverter<S,T> {
    S source;
    T target;
    public BeanConverter(S source, T target) {
        this.source = source;
        this.target = target;
    }
    public void convert(){
        try {
            BeanInfo targetBeanInfo = Introspector.getBeanInfo(target.getClass());
            BeanInfo sourceBeanInfo = Introspector.getBeanInfo(source.getClass());
            for (PropertyDescriptor pd : targetBeanInfo.getPropertyDescriptors()) {
                Method method = pd.getWriteMethod();
                String name = pd.getName();
                if (method != null && !name.equals("class")) {
                    PropertyDescriptor sPd=null;
                    PropertyDescriptor[] sPds=sourceBeanInfo.getPropertyDescriptors();
                    for (int i=0;i<sPds.length;i++){
                        if(name.equals(sPds[i].getName())){
                            sPd=sPds[i];
                            break;
                        }
                    }
                    if(sPd!=null) {
                        Method sMethod = sPd.getReadMethod();
                        try {
                            method.invoke(target, sMethod.invoke(source));
                        }catch (IllegalArgumentException ex){
                            //ex.printStackTrace();
                        }
                    }
                }

            }
        } catch (Exception e) {
            //e.printStackTrace();
        }
    }
}
